package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"platform-ctrl/cache"
	"platform-ctrl/model"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	desc := c.PostForm("desc")
	author := c.PostForm("author")
	if title == "" || desc == "" || author == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段不能为空",
		})
		return
	}

	var article model.Article
	article.Title = title
	article.Desc = desc
	article.Author = author

	err := model.DB.Create(&article).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return

}
func Del(c *gin.Context) {
	id := c.PostForm("id")

	var article model.Article

	err := model.DB.Where("id=?", id).Delete(&article).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "删除失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return

}
func List(c *gin.Context) {
	var article []model.Article

	redis_list_key := "article_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()

	if cacheData == "" {
		model.DB.Find(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &article)
	}
	c.JSON(200, gin.H{
		"code":    200,
		"msg":     "列表展示成功",
		"article": article,
	})
	return
}
